在 C++ 中,資料流不僅是管道;它們是 具有狀態的實體。評估一個 istream 物件,例如 std::cin 作為布林條件,讓我們的程式能適應使用者輸入或外部檔案的不可預測節奏。
1. 資料流的真值
當我們使用 if (std::cin >> val)時,該表達式會傳回 true 僅當資料流仍有效時才成立。若遇到 結尾檔案(EOF) 或遇到無效的資料類型,就會轉為「失敗」狀態,並傳回 false。
2. 鎖定點與探測器
為了追蹤資料變動,我們定義 currVal (我們的狀態鎖定點)以及 val (我們的主動探測器)。邏輯取決於將即將到來的探測器與鎖定點進行比較。一旦不匹配,就會觸發「狀態改變」報告,從而有效實現以最少記憶體處理無限資料。
3. 多次讀取操作
C++ 允許串接資料流讀取: cin >> i >> j;。這會將第一個值讀入 i ,第二個值則讀入 j,提供了一種簡潔的方式來讀取複雜的記錄。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
Exercise 1.17: What happens in the counting program if all input values are equal?
The program crashes due to an infinite loop.
The program prints the count for every single input entered.
The program accumulates the count and prints a single result only after EOF is reached.
The program skips all inputs because no state change is detected.
✅ Correct!
Correct. Since the `val == currVal` condition is always true, the `else` block never triggers until the `while` loop finishes.❌ Incorrect
The `else` block only executes when a *new* value is found; if all are the same, we only see the final summary after the stream ends.QUESTION 2
What does the expression
std::cin >> val return when used in a while loop condition?The integer value that was just read.
A reference to the istream object, which is then evaluated as a boolean.
The number of characters remaining in the buffer.
A pointer to the memory address of val.
✅ Correct!
Exactly! The stream object itself is returned, and C++ checks its state (valid/invalid) to decide if the loop continues.❌ Incorrect
It returns the stream. If the stream encountered an error or EOF, the boolean evaluation becomes false.QUESTION 3
Exercise 1.20: If you use
while (std::cin >> trans) with a Sales_item object, how does the loop detect the end of input?It waits for a specific 'END' string in the transaction data.
The Sales_item class has a built-in timer.
The istream operator for Sales_item is overloaded to return the stream state, allowing EOF detection.
It only stops when it reads a transaction with a price of zero.
✅ Correct!
Correct. Class objects can define how they interact with streams so they behave just like built-in types (int, double).❌ Incorrect
The behavior is consistent with basic types: the stream state determines the loop termination.QUESTION 4
In the syntax
std::cin >> i >> j;, what determines which variable gets the first piece of data?The alphabetical order of variable names.
The variable type (int vs float).
The sequence from left to right.
The compiler's optimization settings.
✅ Correct!
The stream extracts data sequentially. The first value in the buffer goes into the first variable on the left.❌ Incorrect
Streams are processed from left to right, matching the input order.QUESTION 5
What happens if a user types 'ABC' when the program expects
std::cin >> val (where val is an int)?The program converts the characters to their ASCII integer sums.
The stream enters a 'fail' state and the condition
(std::cin >> val) becomes false.The program prompts the user to re-enter the data automatically.
The integer 0 is stored in val and the program continues.
✅ Correct!
Type mismatch causes the stream state to fail, which is why our `while` loops stop gracefully on bad input.❌ Incorrect
Incorrect input doesn't just return 0; it breaks the stream's validity.Mastering Stream Transitions
Analysis of data tracking and class streams
You are developing a transaction logger for a bookstore. You need to read multiple transactions using the Sales_item class. If the input is 'ISBN-001 5 20.0 ISBN-001 2 20.0 ISBN-002 1 15.0', your logic must detect the ISBN change.
Q
1. Provide the model code for reading a set of book sales transactions and writing them to standard output (Exercise 1.20).
Solution:
Solution: cpp #include <iostream> #include "Sales_item.h" int main() { Sales_item trans; while (std::cin >> trans) { std::cout << trans << std::endl; } return 0; }
Solution: cpp #include <iostream> #include "Sales_item.h" int main() { Sales_item trans; while (std::cin >> trans) { std::cout << trans << std::endl; } return 0; }
Q
2. Explain why the program in Exercise 1.20 works for both a single transaction and a thousand transactions without modifying the code.
Solution:
The program uses an **iterative stream processing** model. The `while (std::cin >> trans)` loop continually probes the stream. As long as a valid transaction is available, the loop body executes. It only terminates when the system signals an EOF (End-of-File) or data failure, making it agnostic to the input size.
The program uses an **iterative stream processing** model. The `while (std::cin >> trans)` loop continually probes the stream. As long as a valid transaction is available, the loop body executes. It only terminates when the system signals an EOF (End-of-File) or data failure, making it agnostic to the input size.
Q
3. In a counting logic scenario, what happens if the input has no duplicated values? (Exercise 1.17)
Solution:
If no values are duplicated, the `else` block will execute for every single input after the first `currVal` is set. Each time a new `val` is read, it will not match `currVal`, causing the program to print that the previous value occurred exactly 1 time before resetting the anchor.
If no values are duplicated, the `else` block will execute for every single input after the first `currVal` is set. Each time a new `val` is read, it will not match `currVal`, causing the program to print that the previous value occurred exactly 1 time before resetting the anchor.